using UnityEngine;
using QFramework;

namespace ProjectSurvivor
{
	public partial class Player : ViewController//表示一个挂在场景物体上的控制器（如玩家、刷怪器）。
	{
		float speed = 5;
		public static Player Default;
		void Awake()
		{
			Default = this;
			Time.timeScale = 1f;
		}
		void Start()
		{
			"Hollo".LogInfo();
			Hurt.OnTriggerEnter2DEvent(collider2D =>
			{
				ResKit.Init();
				var hitBox = collider2D.GetComponent<Hurt>();
				if (hitBox)
				{
					if (hitBox.Owner.CompareTag("Enemy"))
					{
						Global.HP.Value--;
						AudioKit.PlaySound("die");
						if (Global.HP.Value <= 0)
						{
							AudioKit.PlaySound("die");
							UIKit.OpenPanel<UIGameOverPlanel>();//打开 UI。
							this.DestroyGameObjGracefully();
						}
					}
				}
			}).UnRegisterWhenGameObjectDestroyed(gameObject);//自动注销
			void UpdataHp()
			{
				HPValue.fillAmount = Global.HP.Value / (float)Global.MaxHP.Value;
			}
			Global.HP.RegisterWithInitValue(hp =>
			{
				UpdataHp();
			}).UnRegisterWhenGameObjectDestroyed(gameObject);
			Global.MaxHP.RegisterWithInitValue(hp =>
			{
				UpdataHp();
			}).UnRegisterWhenGameObjectDestroyed(gameObject);
		}
		bool mFaceRight =true;
		void Update()
		{
			var h = Input.GetAxis("Horizontal");
			var v = Input.GetAxis("Vertical");
			if (h == 0 && v == 0)
			{
				if (mFaceRight)
				{
					Square.Play("Playeridel_right");
				}
				else
				{
					Square.Play("Playeridel_left");
				}

			}
			else
			{
				AudioKit.PlaySound("walk");
				
				if (h > 0)
				{
					
					mFaceRight = true;
				}
				else
				{
					
					mFaceRight = false;
				}
				if (!mFaceRight)
				{
			
					Square.Play("Playerwalk_left");
				}
				else
				{
		
					Square.Play("Playerwalk_right");
				}
				
			}


			var v2 = new Vector2(h, v).normalized*speed*Global.speed.Value;
			rigidBody.velocity = Vector2.Lerp(rigidBody.velocity, v2, 1 - Mathf.Exp(-Time.deltaTime * 5));
		}
        void OnDestroy()
        {
			
			Default = null;
        }
    }
}
